<?php

class SupplierDeliveryRequestsController extends AppController {

    var $name = 'SupplierDeliveryRequests';
    var $viewPath = 'suppliers/delivery/requests';
    var $pageTitle = 'Delivery Information';
    var $uses = array('DeRH', 'DeR', 'CustomerSupplier', 'CustProductSite', 'DeRStatus');
    var $paginate = array(
        'DeRH' => array(
            'order' => 'DeRH.id DESC'
        )
    );

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'supplier_delivery_requests');

        $this->_checkPrintView();
    }

    function display() {
        parent::display('DeRH');
        $this->paginate['DeRH']['contain'] = array('Customer', 'Site', 'DeRStatus', 'DeRtH');

        $this->paginate['DeRH']['conditions']['DeRH.supplier_id'] = $this->Auth->user('supplier_id');

        $op = array(
            'request_no' => 'LIKE',
            'request_by' => 'LIKE',
        );

        // มีการ search โดยใช้ request_no ทำให้เป็นพิมพ์ใหญ่
        if (!empty($this->data['DeRH']['request_no'])) {
            $this->data['DeRH']['request_no'] = strtoupper($this->data['DeRH']['request_no']);
        }

        // search โดย received & released
        if (!empty($this->data['DeRH']['delivery_request_status_id']) && $this->data['DeRH']['delivery_request_status_id'] == 99) {
//            $this->paginate['DeRH']['conditions']['DeRH.delivery_request_status_id'] = DeRStatus::RECEIVED;
            $this->data['DeRH']['delivery_request_status_id'] = DeRStatus::RECEIVED;
            $op['delivery_request_status_id'] = '>=';
        }

        $this->_checkBetweenSearch('DeRH', 'request_date');
        $this->_paging('DeRH', $op);
    }

    function save() {
        $mode = $this->data['mode'];
        $id = $this->data['DeRH']['id'];

        if ($mode == 'acknowledge') {
            $is_success = $this->_acknowledge_request();
        } elseif ($mode == 'request_cancel') {
            $is_success = $this->_request_cancel();
        }

        if (!empty($this->data['DeRH']['supplier_comment'])) {
            $this->DeRH->id = $this->data['DeRH']['id'];
            $is_success &= $this->DeRH->saveField('supplier_comment', $this->data['DeRH']['supplier_comment']);
        }


        if ($is_success) {
            $this->Session->setFlash("Delivery request save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Delivery request save fail!!!.", 'flash/fail');
        }

        $this->setAction('view', $id);
    }

    function _acknowledge_request() {
        $id = $this->data['DeRH']['id'];
        $is_success = true;
        $status_id = $this->data['DeRH']['delivery_request_status_id'];

        $this->DeRH->query('BEGIN');

        if ($this->DeRH->saveAll($this->data)) {
            $this->DeRH->id = $id;

            $is_success &= $this->DeRH->saveField('delivery_request_status_id', DERStatus::READ);

//                // เช็คว่า จำนวน partial หรือไม่
//                $is_partial = false;
//                $deRs = $this->DeR->findAllByDeliveryRequestHeadId($this->data['DeRH']['id']);
//                $count = count($deRs);
//                for ($i = 0; $i < $count; ++$i) {
//                    if ($this->data['DeR'][$i]['delivery_qty'] != $deRs[$i]['DeR']['request_qty']) {
//                        $is_partial = true;
//                    }
//                }
//                $this->DeRH->saveField('is_partial', $is_partial);
        } else {
            $is_success = false;
        }

        if ($is_success) {
            $this->Session->setFlash("Delivery request save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Delivery request save fail!!!.", 'flash/fail');
        }
        return $is_success;
    }

    function _request_cancel() {
        $this->DeRH->id = $this->data['DeRH']['id'];
        $this->DeRH->saveField('request_cancel_date', date('Y-m-d'));
        return $this->DeRH->saveField('delivery_request_status_id', DERStatus::REQUEST_TO_CANCEL);
    }

    function delivery($id) {
        $this->DeRH->query("BEGIN");
        $this->DeRH->id = $id;
        $is_success = $this->DeRH->saveField('delivery_request_status_id', DeRStatus::ON_DELIVERY);
        $is_success &= $this->DeRH->saveField('delivery_date', date('Y-m-d'));

        // On Delivery ปรับ CPS ลด Request Qty
        $this->DeR->contain();
        $data = $this->DeR->findAllByDeliveryRequestHeadId($id);
        foreach ($data as $dr) {
            $this->CustProductSite->id = $dr['DeR']['cust_product_site_id'];
            // ลด request_qty ที่ CPS
            $request_qty = $this->CustProductSite->field('request_qty');
            $is_success &= $this->CustProductSite->saveField('request_qty', $request_qty - $dr['DeR']['request_qty']);
        }

        if ($is_success) {
            $this->DeRH->query("COMMIT");
        } else {
            $this->DeRH->query("ROLLBACK");
        }
        $this->redirect('print_view/' . $id);
    }

    function view($id) {
        if ($id != null) {
            $this->DeRH->contain(array('Customer', 'Site', 'DeRtH', 'DeR' => array('Product' => array('Unit'), 'CustProductSite'), 'DeRStatus'));
            $this->data = $this->DeRH->findById($id);

            $this->_neighbors($id, $this->DeRH, array('fields' => array('id', 'request_no')));

            if (isset($this->passedArgs['edit'])) {
                $this->set('mode', 'edit');
            } elseif (isset($this->passedArgs['acknowledge'])) {
                $this->set('mode', 'acknowledge');
                $this->DeRStatus->id = DeRStatus::ACKNOWNLEDGE;
                $this->data['DeRStatus']['title'] = $this->DeRStatus->field('title');
            } elseif (isset($this->passedArgs['request_cancel'])) {
                $this->set('mode', 'request_cancel');
                $this->DeRStatus->id = DeRStatus::REQUEST_TO_CANCEL;
                $this->data['DeRStatus']['title'] = $this->DeRStatus->field('title');
            } else {
                $this->set('mode', 'view');
            }
            $this->set('status_id', $this->data['DeRH']['delivery_request_status_id']);
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->DeRH->contain(array('Supplier', 'Customer', 'Site', 'DeRStatus', 'DeR' => array('Product' => array('Unit'), 'CustProductSite')));
        $this->data = $this->DeRH->findById($id);
    }

    function popup_search() {
        parent::popup_search();

        $statuses = $this->DeRStatus->find('list');
        $statuses[99] = 'Received & Released';
        $this->set('statuses', $statuses);
        $this->set('customers', $this->CustomerSupplier->listCustomerBySupplierId($this->Auth->user('supplier_id')));
        $this->set('popupWidth', 500);
    }

    /**
     * สำหรับ Vendor หรือ ITS เข้ามาเช็ค ว่าออก invoice แล้วหรือยัง
     * @param int $id
     * @param boolean $is_invoiced
     */
    function set_invoiced($id, $is_invoiced, $invoice_no = null) {
        $this->DeRH->id = $id;
        // หน้า view ส่ง true มาจะเป็น String
        $this->DeRH->saveField('is_invoiced', $is_invoiced == 'true');

        // ถ้า invoice เข้ามา Save invoice no ด้วย
        if ($is_invoiced == 'true') {
            $this->DeRH->saveField('invoice_no', $invoice_no);
        } else { // ถ้าไม่ใช่ลบ invoice no ออก
            $this->DeRH->saveField('invoice_no', null);
        }
//        $this->DeRH->saveField('invoice_collector_id', $this->Auth->user('id'));

        $this->layout = 'ajax';
        $this->set('value', $this->DeRH->field('is_invoiced') == true ? 'Yes' : 'No');
        $this->viewPath = 'elements';
        $this->render('ajax/inplace_editor');
    }

    /**
     * นับจำนวน Delivery Request ที่มี status เป็น On REQUEST
     */
    function get_on_request_count() {
        return $this->DeRH->find('count', array(
           'conditions' => array(
               'DeRH.supplier_id' => $this->Auth->user('supplier_id'),
               'delivery_request_status_id' => DeRStatus::ON_REQUEST
           )
        ));
    }

}

?>
